package com.superyee.commonlib.http;



import com.superyee.commonlib.utils.AppLog;

import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class LoggingInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {

        Request request = chain.request();
        StringBuilder stringBuilder = new StringBuilder("  \n######################################## S T A R T ############################################\n");
        String content = null;
        try {
            RequestBody requestBody = request.body();
            if (requestBody != null) {
                if (requestBody instanceof FormBody) {
                    FormBody body = (FormBody) request.body();
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < body.size(); i++) {
                        sb.append(body.encodedName(i) + "=" + body.encodedValue(i) + ",");
                    }
                    content = sb.toString();
                } else if (requestBody instanceof MultipartBody) {
                    MultipartBody body = (MultipartBody) request.body();
                    StringBuilder sb = new StringBuilder();
                    List<MultipartBody.Part> list = body.parts();
                    for (int i = 0; i < list.size(); i++) {
                        sb.append(list.get(i).headers().toString() + "=" + list.get(i).body().toString());
                    }
                    content = sb.toString();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        stringBuilder.append(String.format("Sending request %s on %s%n%sRequestParams: %s", request.url(), chain.connection(), request.headers(), content)).append("\n\n");

        long t1 = System.nanoTime();
        Response response = chain.proceed(chain.request());
        long t2 = System.nanoTime();
        stringBuilder.append(String.format(Locale.getDefault(), "Received response for %s in %.1fms resultCode %s",
                response.request().url(), (t2 - t1) / 1e6d, response.code())).append("\n\n");

        //下载文件会内存溢出
        okhttp3.MediaType mediaType = response.body().contentType();
        if (response.body().contentLength() > 0.5 * 1024 * 1024) {
            stringBuilder.append("可能正在下载文件\n\n").append(" \n###########################################  E N D ####################################################\n\n");
            AppLog.printD("http", stringBuilder.toString());
            return response;
        }
        String result = response.body().string();
        stringBuilder.append(result).append("\n\n");
        long length = stringBuilder.length();
        if (length <= 2048)
            AppLog.printD("http", unicodetoString(stringBuilder.toString()));
        else {
            while (stringBuilder.length() > 2048) {
                String logContent = stringBuilder.substring(0, 2048);
                stringBuilder.delete(0, 2048);
                AppLog.printD("http", unicodetoString(logContent));
            }
            AppLog.printD("http", unicodetoString(stringBuilder.toString()));
            AppLog.printD("http", "  \n#############################################  E N D ################################################\n\n");
        }
        return response.newBuilder()
                .body(okhttp3.ResponseBody.create(mediaType, result))
                .build();
    }

    private final Pattern REG_UNICODE = Pattern.compile("[0-9A-Fa-f]{4}");

    public String unicodetoString(String str) {
        StringBuilder sb = new StringBuilder();
        int len = str.length();
        for (int i = 0; i < len; i++) {
            char c1 = str.charAt(i);
            if (c1 == '\\' && i < len - 1) {
                char c2 = str.charAt(++i);
                if (c2 == 'u' && i <= len - 5) {
                    String tmp = str.substring(i + 1, i + 5);
                    Matcher matcher = REG_UNICODE.matcher(tmp);
                    if (matcher.find()) {
                        sb.append((char) Integer.parseInt(tmp, 16));
                        i = i + 4;
                    } else {
                        sb.append(c1).append(c2);
                    }
                } else {
                    sb.append(c1).append(c2);
                }
            } else {
                sb.append(c1);
            }
        }
        return sb.toString();
    }
}